(function(){
    var CommonUtils = window.CommonUtils = function(){
        return new CommonUtils.prototype.init();
    };
    CommonUtils.fn = CommonUtils.prototype = {
        TOKEN:null,//登录TOKEN
        init:function () {
            this.initToken();
            return this;
        },
    };
    //获取登录token
    CommonUtils.getToken=function () {
        return 'Bearer '+this.TOKEN;
    };
    //获取服务器地址
    CommonUtils.getSite=function () {
        return "http://"+window.location.host+"/pmap/";
    };
    CommonUtils.getSite2=function () {
        return "http://"+window.location.host;
    };
    CommonUtils.getAdminSite=function () {
        return "http://"+window.location.host+"/admin/";
    };
    CommonUtils.arcgisServerUrl=function () {
        // return "http://112.54.43.227:92/arcgis/rest/services";
        return "http://192.168.1.248:6080//arcgis/rest/services";
    };
    //配置ArcGIS跨域IP,
    CommonUtils.getProxyIP=function () {
        var ips=[];
        ips.push("localhost:8080");
        ips.push("localhost");
        return ips;
    };
    CommonUtils.getRegionGemoUrl=function () {
        return "http://"+window.location.host+"/pmap/common/proxy.jsp?"+"http://218.85.80.181:20002/Grid/api/findGridInfo.xhtml";
    }
    CommonUtils.getProxyUrl = function () {
        return "http://"+window.location.host+"/pmap/common/proxy.jsp";
    };

    CommonUtils.getExceptionMsg=function(){
        return "操作失败，请联系系统管理员";
    };
    CommonUtils.getPageRows=function(){
        return 10;
    };

    /**
     * 处理服务器返回结果
     * @param res
     * @returns {boolean}
     */
    CommonUtils.handlerRes=function(res){
        if(res.code!="200"){//只有200的时候请求成功
            alert(res.msg);
            return false;
        }
        return true;
    };
    /**
     * 配置系统面积单位
     * ratio是相对平方米的换算
     */
    CommonUtils.getAreaUnit=function () {
        return [
            {
                "name":"square",
                "title":"平方米",
                "ratio":1
            },{
                "name":"mu",
                "title":"亩",
                "ratio":0.0015
            },
            // {
            //     "name":"squarekilometres",
            //     "title":"平方千米",
            //     "ratio":0.000001
            // },
    ];
    };

    /**
     * 判断是否为空
     * @returns {boolean}
     */
    CommonUtils.isEmpty=function(res){
        return !!(res == null || res.trim() == "" || res == undefined);
    };


    /**参数说明：
     * 根据长度截取先使用字符串，超长部分追加…
     * str 对象字符串
     * len 目标字节长度
     * 返回值： 处理结果字符串
     */
    CommonUtils.cutString=function(str, len) {
        //length属性读出来的汉字长度为1
        if(str.length*2 <= len) {
            return str;
        }
        var strlen = 0;
        var s = "";
        for(var i = 0;i < str.length; i++) {
            s = s + str.charAt(i);
            if (str.charCodeAt(i) > 128) {
                strlen = strlen + 2;
                if(strlen >= len){
                    return s.substring(0,s.length-1) + "...";
                }
            } else {
                strlen = strlen + 1;
                if(strlen >= len){
                    return s.substring(0,s.length-2) + "...";
                }
            }
        }
        return s;
    }


    /**
     * 判断是否为json格式
     * @param res
     * @returns {boolean}
     */
    CommonUtils.isJson=function (res) {
        var isjson = typeof(res) == "object" && Object.prototype.toString.call(res).toLowerCase() == "[object object]" && !res.length
        return isjson;
    }


    /**
     * 判断是否是数字
     * @param val
     * @returns {boolean}
     */
    CommonUtils.isNumber=function(val){

        if (parseFloat(val).toString() == "NaN") {

            return false;
        } else {
            return true;
        }
    }

    //分析url
    CommonUtils.parseURL=function(url) {
        var a = document.createElement('a');
        a.href = url;
        return {
            source: url,
            protocol: a.protocol.replace(':', ''),
            host: a.hostname,
            port: a.port,
            query: a.search,
            params: (function () {
                var ret = {},
                    seg = a.search.replace(/^\?/, '').split('&'),
                    len = seg.length, i = 0, s;
                for (; i < len; i++) {
                    if (!seg[i]) { continue; }
                    s = seg[i].split('=');
                    ret[s[0]] = s[1];
                }
                return ret;

            })(),
            file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
            hash: a.hash.replace('#', ''),
            path: a.pathname.replace(/^([^\/])/, '/$1'),
            relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
            segments: a.pathname.replace(/^\//, '').split('/')
        };
    };

    /**
     * 替换myUrl中的同名参数值
     * @param strUrl http://abc.com:8080/dir/index.html?id=255&m=hello#top
     * @param newParams { id: 101, m: "World", page: 1,"page":2 }
     * @returns {string}
     */
    CommonUtils.replaceUrlParams=function(strUrl, newParams) {
        var myUrl=CommonUtils.parseURL(strUrl);
        for (var x in newParams) {
            var hasInMyUrlParams = false;
            for (var y in myUrl.params) {
                if (x.toLowerCase() == y.toLowerCase()) {
                    myUrl.params[y] = newParams[x];
                    hasInMyUrlParams = true;
                    break;
                }
            }
            //原来没有的参数则追加
            if (!hasInMyUrlParams) {
                myUrl.params[x] = newParams[x];
            }
        }
        var _result = myUrl.protocol + "://" + myUrl.host + ":" + myUrl.port + myUrl.path + "?";

        for (var p in myUrl.params) {
            _result += (p + "=" + myUrl.params[p] + "&");
        }

        if (_result.substr(_result.length - 1) == "&") {
            _result = _result.substr(0, _result.length - 1);
        }

        if (myUrl.hash != "") {
            _result += "#" + myUrl.hash;
        }
        return _result;
    };

    /**
     * 设置登录cookie
     * @param name
     * @param value
     * @param expires
     */
    CommonUtils.setCookie=function (name, value, expires) {
        var cookieString = name + "=" + encodeURIComponent(value) + ";path=/";
        if (expires) {
            var exp = new Date();
            exp.setTime(exp.getTime() + expires * 60 * 60 * 1000);
            cookieString += ";expires=" + exp.toGMTString();
        }
        document.cookie = cookieString;
    };

    //删除cookies
    CommonUtils.delCookie=function (name) {
        CommonUtils.setCookie(name, "", -1);
    };
    /*获取cookie值*/
    CommonUtils.getCookie=function(name) {
        var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
        if (arr = document.cookie.match(reg))
            return decodeURIComponent(arr[2]);
        else
            return null;
    };
    //获取当前日期
    CommonUtils.getCurrentDate=function() {
        var myDate = new Date();
        var year=myDate.getFullYear(); //获取完整的年份(4位,1970-????)
        var month=myDate.getMonth()+1; //获取当前月份(0-11,0代表1月)
        var date=myDate.getDate(); //获取当前日(1-31)
        var mytime=year+"-"+month+"-"+date; //获取当前时间
        return mytime;
    };
    //计算日期差值
    CommonUtils.getTimeDifcHours=function(start,end) {
        var starts = new Date(start),
            ends = new Date(end);
        if (starts.getTime() > ends.getTime()){
            console.log("start的时间小于end的时间");
            return message = "";
        }
        var date3=ends.getTime()-starts.getTime(); //时间差的毫秒数
        //计算出相差天数
        var days=Math.floor(date3/(24*3600*1000));
        //计算出小时数
        var leave1=date3%(24*3600*1000);    //计算天数后剩余的毫秒数
        var hours=Math.floor(leave1/(3600*1000));

        var message=days+"天"+hours+"小时";
        return message;
    };

    CommonUtils.fn.init.prototype = CommonUtils.fn;
})();

String.prototype.trim=function(){
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.ltrim=function(){
    return this.replace(/(^\s*)/g,"");
}
String.prototype.rtrim=function(){
    return this.replace(/(\s*$)/g,"");
}

String.prototype.endWith=function(str){
    if(str==null||str==""||this.length==0||str.length>this.length)
        return false;
    if(this.substring(this.length-str.length)==str)
        return true;
    else
        return false;
    return true;
}
$.getUrlParam = function(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
        return unescape(r[2]);
    return null;
}







